package com.xusiyan08.service;

import com.xusiyan08.dto.UserUpdateRequest;
import com.xusiyan08.entity.AdminAction;
import com.xusiyan08.entity.Item;
import com.xusiyan08.entity.User;
import com.xusiyan08.entity.enums.ActionType;
import com.xusiyan08.entity.enums.TargetType;
import com.xusiyan08.repository.AdminActionRepository;
import com.xusiyan08.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AdminService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private AdminActionRepository adminActionRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private ItemService itemService;

    private void logAdminAction(Long adminId, TargetType targetType, Long targetId, ActionType actionType, String reason) {
        User admin = userRepository.findById(adminId)
                .orElseThrow(() -> new RuntimeException("Admin user not found with id: " + adminId));

        AdminAction action = new AdminAction();
        action.setAdmin(admin);
        action.setTargetType(targetType);
        action.setTargetId(targetId);
        action.setActionType(actionType);
        action.setReason(reason);
        action.setCreatedAt(LocalDateTime.now());
        adminActionRepository.save(action);
    }


    public List<User> getAllUsers() {
        return userService.getAllUsers();
    }

    @Transactional
    public void deleteUser(Long userId, Long adminId, String reason) {
        userService.deleteUser(userId);
        logAdminAction(adminId, TargetType.USER, userId, ActionType.DELETE, reason);
    }

    public List<Item> getPendingItems() {
        return itemService.getItemsByStatus(Item.Status.审核中);
    }

    @Transactional
    public Item approveItem(Long itemId, Long adminId, String reason) {
        Item item = itemService.updateItemStatus(itemId, Item.Status.出售中);
        if (item != null) {
            logAdminAction(adminId, TargetType.ITEM, itemId, ActionType.APPROVE, reason);
        }
        return item;
    }

    @Transactional
    public Item rejectItem(Long itemId, Long adminId, String reason) {
        Item item = itemService.updateItemStatus(itemId, Item.Status.已下架);
        if (item != null) {
            logAdminAction(adminId, TargetType.ITEM, itemId, ActionType.REJECT, reason);
        }
        return item;
    }

    @Transactional
    public void deleteItem(Long itemId, Long adminId, String reason) {
        itemService.deleteItem(itemId);
        logAdminAction(adminId, TargetType.ITEM, itemId, ActionType.DELETE, reason);
    }

    public List<Item> getAllItemsForAdmin() {
        return itemService.getAllItemsWithDetails();
    }

    public User getUserById(Long userId) {
        return userRepository.findById(userId).orElse(null);
    }

    public User updateUser(Long userIdToUpdate, UserUpdateRequest updateRequest, Long adminId, String notes) {
        User user = userRepository.findById(userIdToUpdate).orElse(null);
        if (user == null) {
            // 可以选择抛出更具体的异常，例如 EntityNotFoundException
            // 或者根据业务需求返回 null 或其他错误指示
            System.err.println("User not found with ID: " + userIdToUpdate);
            return null;
        }

        boolean updated = false;
        if (updateRequest.getStudentId() != null && !updateRequest.getStudentId().equals(user.getStudentId())) {
            user.setStudentId(updateRequest.getStudentId());
            updated = true;
        }
        if (updateRequest.getNickname() != null && !updateRequest.getNickname().equals(user.getNickname())) {
            user.setNickname(updateRequest.getNickname());
            updated = true;
        }
        if (updateRequest.getPhone() != null && !updateRequest.getPhone().equals(user.getPhone())) {
            user.setPhone(updateRequest.getPhone());
            updated = true;
        }

        if (updated) {
            user.setUpdatedAt(LocalDateTime.now());
            User savedUser = userRepository.save(user);

            // 记录管理员操作
            logAdminAction(adminId, TargetType.USER, savedUser.getUserId(), ActionType.UPDATE, notes);
            return savedUser;
        } else {
            // 如果没有任何字段被实际更新，可以选择直接返回原用户对象
            // 或者根据业务需求返回特定指示
            return user; 
        }
    }
}